package blog_grpc

import (
	context "context"
	"fmt"
	"strconv"

	"gitee.com/yangwencheng/vblog/apps/blog"
	"gitee.com/yangwencheng/vblog/apps/blog/blog_grpc/pb"
	"gitee.com/yangwencheng/vblog/logger"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

func (h *Handler) CreateBlog(ctx context.Context, req *pb.CreateBlogRequest) (*pb.Blog, error) {

	cbr := blog.NewCreateBlogRequest()
	cbr.Content = req.Content
	cbr.Author = req.Author
	cbr.Status = blog.STATUS(req.Status)
	cbr.Title = req.Title
	// 转换tag
	for k, v := range req.Tags {
		if intV, err := strconv.Atoi(v); err == nil {
			cbr.Tags[k] = intV
		} else {
			cbr.Tags[k] = v
		}
	}
	blog, err := h.srv.CreateBlog(ctx, cbr)
	if err != nil {
		return nil, status.Errorf(codes.Aborted, err.Error())
	}
	grpcBlog := &pb.Blog{}
	grpcBlog.Author = blog.Author
	grpcBlog.Content = blog.Content
	grpcBlog.Status = pb.STATUS(blog.Status)
	grpcBlog.Title = blog.Title
	grpcBlog.Id = blog.ID
	grpcBlog.CreatedAt = blog.CreatedAt
	grpcBlog.UpdatedAt = blog.UpdatedAt
	grpcBlog.Tags = make(map[string]string)
	for k, v := range blog.Tags {
		grpcBlog.Tags[k] = fmt.Sprintf("%v", v)
	}

	logger.GetLogger().Info().Any("blog", blog).Msg("grpc成功")
	return grpcBlog, nil
}
